/******************************************************************************
 * Copyright (C) 2017 Chengdu Dlhd information industry co. LTD.
 * All Rights Reserved.
 * 本软件为成都顶联互动信息产业有限公司开发研制。未经本公司正式书面同意，其他任何个人、团体不得使用、复制、修改或发布本软件.
 *****************************************************************************/
package net.dgg.dggcloud.service.iboss.service.sc;

import net.dgg.dggcloud.core.minidao.hibernate.dao.IGenericBaseCommonDao;
import net.dgg.dggcloud.service.common.base.SessionManager;
import net.dgg.dggcloud.service.common.base.service.BaseService;
import net.dgg.dggcloud.service.entity.org.OrganizationEntity;
import net.dgg.dggcloud.service.entity.user.User;
import net.dgg.dggcloud.service.iboss.constant.*;
import net.dgg.dggcloud.service.iboss.dao.sc.AllProOrderDao;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowNode;
import net.dgg.dggcloud.service.iboss.entity.ScProFlowOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProNodeOperating;
import net.dgg.dggcloud.service.iboss.entity.ScProOrder;
import net.dgg.dggcloud.service.jrcrm.entity.pro.Product;
import net.dgg.dggcloud.service.jrcrm.service.cms.BillNumberRuleService;
import net.dgg.dggcloud.service.jrcrm.service.cms.CustomerRecordService;
import net.dgg.dggcloud.service.jrcrm.service.cms.MessageService;
import net.dgg.dggcloud.service.jrcrm.service.orf.api.OrderApiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @class_name: AllProOrderService
 * @package: net.dgg.dggcloud.service.iboss.service.sc
 * @describe: TODO 全部生产订单-service层
 * @creat_user: 代杨
 * @creat_date: 2017/11/24
 * @creat_time: 10:01
 **/
@Service
public class AllProOrderService extends BaseService {
    @Resource
    private AllProOrderDao allProOrderDao;
    @Resource(name = "miniDaoHiberCommonDao")
    protected IGenericBaseCommonDao repository;
    @Autowired
    private BillNumberRuleService billNumberRuleService;
    @Autowired
    private ScProOrderTimeStateService scProOrderTimeStateService;
    @Autowired
    private NodeManagerService nodeManagerService;
    @Autowired
    private CustomerRecordService customerRecordService;
    @Autowired
    private OrderApiService orderApiService;
    @Autowired
    private MessageService messageService;
    @Autowired
    private ScProOrderService scProOrderService;
    @Autowired
    private WaitAllocationService waitAllocationService;
    /**
     * 全部生产订单List<Map></br>
     *
     * @param map</br>
     * @return 集合</br>
     */
    public List<Map> listAllProOrderByMap(Map map) {
        return allProOrderDao.listAllProOrderByMap(map);
    }

    /**
     * @Title:
     * @Description: TODO 查询父产品列表集合
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/2/26
     **/
    public List<Map> searchParentProductMap() {
        return allProOrderDao.searchParentProductMap();
    }
    /**
     * @Title:
     * @Description: TODO 查询产品列表集合
     * @param:
     * @return:
     * @throw:
     * @author: 代杨
     * @creat_date: 2018/2/26
     **/
    public List<Map> searchProductMap() {
        return allProOrderDao.searchProductMap();
    }
    /**
     * @Title:
     * @Description: TODO 全部订单统计count
     * @param:
     * @return:
     * @throw:
     * @creat_user: 代杨
     * @creat_date: 2017/12/5
     **/
    public Integer countAllProOrderByMap(Map map) {
        return allProOrderDao.countAllProOrderByMap(map);
    }

    /**
     * @Title:
     * @Description: TODO 根据ID查询生产订单
     * @param:
     * @return:
     * @throw:
     * @creat_user: 代杨
     * @creat_date: 2017/12/5
     **/
    public ScProOrder queryScProOrderById(Long id) {
        ScProOrder scProOrder = repository.get(ScProOrder.class, id);
        return scProOrder;
    }

    /**
     * @Title:
     * @Description: TODO 查询出当前生产订单的剩余节点
     * @param:
     * @return:
     * @throw:
     * @creat_user: 代杨
     * @creat_date: 2017/12/8
     **/
    public List<Map> querySurplusNode(Map map) {
        List<Map> retmap = allProOrderDao.listSurplusNodeByMap(map);
        return retmap;
    }
    /**
     * @Title:
     * @Description: TODO 新增渠道
     * @param:
     * @return:
     * @throw:
     * @creat_user: 代杨
     * @creat_date: 2017/12/6
     **/
    public void addCreatenewchannelorder(Map map, User user) {
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");

        long id = this.keyWorker.nextId();
        Long scorderid = Long.parseLong(map.get("scorderid").toString());
        ScProOrder scProOrder = queryScProOrderById(scorderid);
        Assert.isTrue(scProOrder.getFlowUserId().equals(user.getId()), "只能由流程人员新增渠道！");
        Long processerId = Long.parseLong(map.get("processerId").toString());
        User flowUser = map.get("processerId") == null ? null : this.repository.get(User.class, processerId); // 流程人员
        OrganizationEntity org = user.getOrgId() == null ? null : this.repository.get(OrganizationEntity.class, flowUser.getOrgId());


        ScProOrder scorder = new ScProOrder();
//        scorder = scProOrder;
        scorder.setId(id);
        if(flowUser!=null){
            scorder.setFlowUserId(flowUser.getId()); //流程人员
            scorder.setFlowUserName(String.format("%s%s", flowUser.getName(), org == null ? "" : "(" + org.getName() + ")"));
            scorder.setFlowDeptId(flowUser.getOrgId());
        }
        scorder.setFlowDeptName(org == null ? null : org.getName());
        scorder.setChannelId(map.get("channelId") == null ? scProOrder.getChannelId() : Long.parseLong(map.get("channelId").toString())); //渠道
        scorder.setProductId(map.get("productId") == null ? scProOrder.getProOrderId() : Long.parseLong(map.get("productId").toString()));//产品
        if (scorder.getProductId() != null) {
            Product product = this.repository.get(Product.class, scorder.getProductId());
            Assert.notNull(product, "未查询到该产品，请刷新页面！");
            scorder.setBtCode(product.getType()); // 根据产品设置业态码
        }
        scorder.setSubBranch(map.get("subbranch") == null ? scProOrder.getSubBranch() : map.get("subbranch").toString()); //支行
        scorder.setContractNo(map.get("contractno") == null ? scProOrder.getContractNo() : map.get("contractno").toString());
        scorder.setLoansAmount(map.get("loansamount") == null ? scProOrder.getLoansAmount() : Math.round(Double.parseDouble(map.get("loansamount").toString())* 1000000));
        scorder.setCustomerId(scProOrder.getCustomerId());//客户id
        scorder.setCustomerName(scProOrder.getCustomerName());//客户名称
        scorder.setCustomerPhone(scProOrder.getCustomerPhone()); //客户电话
        scorder.setSigningUserId(scProOrder.getSigningUserId()); // 签单人信息
        scorder.setSigningUserName(scProOrder.getSigningUserName());
        scorder.setSigningDeptId(scProOrder.getSigningDeptId()); // 签单人部门
        scorder.setSigningDeptName(scProOrder.getSigningDeptName());
        scorder.setOrderId(scProOrder.getOrderId());//销售主订单ID
        scorder.setOrderNo(scProOrder.getOrderNo());//销售主订单编号
        scorder.setProOrderId(scProOrder.getProOrderId()); // 生产主订单id
        scorder.setProOrderNo(scProOrder.getProOrderNo());// 生产主订单编号
        scorder.setIsbelongrisk(scProOrder.getIsbelongrisk());
        scorder.setOriginCode(OriginCodeSource.SC_ORIGINCODE_BUSINESS);

//        scorder.setBtCode(scProOrder.getBtCode()); //业态code
        scorder.setOrderBusinessNo(this.billNumberRuleService.updateBillNumberByCode(OrderNoConstant.NO_CODE));  // 生产子订单子订单编号
        scorder.setPlaceOrderTime(scProOrder.getPlaceOrderTime()); // 签单时间
        scorder.setStatus(ScStatusConstant.RECEIVE_WAITING); // "SCORDER_STATUS01"  待接收
        scorder.setCreateUser(user);
        this.repository.save(scorder);

        waitAllocationService.updateUserSetting(scorder, "2"); //加1
        String[] vals = new String[1];
        vals[0] = String.valueOf(scorder.getOrderBusinessNo());
        String tempCode = MsgCodeConstant.SC_DJS_MSG;
        //String tem = "订单{0}需要接收，请及时查看";
        messageService.sendMessageReady(flowUser, SessionManager.getCurrentUser(), vals, tempCode);//消息提醒

        //操作记录
        ScProFlowOperating scProFlowOperating = new ScProFlowOperating();
        scProFlowOperating.setOperationType(ScOperationConstant.OPERATION_ORDER_ADDCHANNEL); // SCORDER_CZ_CODE2 新增渠道
        scProFlowOperating.setProProductId(scorder.getId());
        scProFlowOperating.setProProductNo(scorder.getOrderBusinessNo());
        scProFlowOperating.setFlowUserId(scorder.getFlowUserId());
        scProFlowOperating.setFlowUserName(scorder.getFlowUserName());
        scProFlowOperating.setStatus(scorder.getStatus());
        scProFlowOperating.setOperation("新增渠道");
        scProFlowOperating.setCreateUser(user);
        scProFlowOperating.setId(this.keyWorker.nextId());
        this.repository.save(scProFlowOperating);

        //发送短信给流程
        this.scProOrderService.sendSmsMsgToUser(scProOrder.getWaitingReceiverId(), tempCode, scProOrder.getOrderBusinessNo());
    }

    /**
     * @Title:
     * @Description: TODO 更新节点信息保存
     * @param:
     * @return:
     * @throw:
     * @creat_user: 代杨
     * @creat_date: 2017/12/6
     **/
    public void saveUpdateNodeInfo(Map map, User user) throws Exception {
        Assert.notNull(user, "当前用户获取失败，请刷新重新登录！");

        long id = this.keyWorker.nextId();
        Long scorderid = Long.parseLong(map.get("scorderid").toString());
        ScProOrder scOrder = queryScProOrderById(scorderid);
        Assert.notNull(scOrder, "生产订单关联错误！");
        Assert.isTrue(scOrder.getStatus().equals(ScStatusConstant.ORDER_PROCESS)||scOrder.getStatus().equals(ScStatusConstant.ORDER_COMPLETE), "该订单状态无法进行更新，请确认订单是否处于办理中或已成单状态！");
        scOrder.setUpdaterUser(user);

        ScProNodeOperating scProNodeOperating = new ScProNodeOperating();
//        Assert.isTrue(idList.size() > 0, "订单ID数据错误");
        scProNodeOperating.setId(this.keyWorker.nextId());
        scProNodeOperating.setProProductId(scOrder.getId());
        scProNodeOperating.setProProductNo(scOrder.getOrderBusinessNo());
        scProNodeOperating.setCreateUser(user);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat nextsdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ScProFlowNode scProFlowNode = nodeManagerService.queryScProNodeById(Long.parseLong(map.get("completenodeid").toString()));
        Assert.notNull(scProFlowNode, "生产订单节点关联错误！");
        Map tjmap = new HashMap();
        tjmap.put("proid", scorderid+"");
        tjmap.put("noedid", map.get("completenodeid").toString());
        List<Map> nowNodeMap = nodeManagerService.queryScOperationByMap(tjmap);
        Assert.isTrue(nowNodeMap.size() ==0, "当前订单节点已被更新，请勿重复操作！");

        if (scOrder.getLatestNodeId() != null ) {
            scProNodeOperating.setLastNodeId(scOrder.getLatestNodeId());//上个完成节点id
        }
        if (scOrder.getLatestNode() != null && !scOrder.getLatestNode().equals("")) {
            scProNodeOperating.setLastNodeName(scOrder.getLatestNode());//上一个完成节点名称
        }
        if (scOrder.getLastNodeTime() != null ) {
            scProNodeOperating.setLastNodeTime(scOrder.getLastNodeTime());//上一个完成节点时间
        }

        if (map.get("completenodeid") != null && !map.get("completenodeid").equals("")) {//完成节点noidid
            scOrder.setLatestNodeId(Long.parseLong(map.get("completenodeid").toString()));
            scProNodeOperating.setNoedId(Long.parseLong(map.get("completenodeid").toString()));
        }
        if (map.get("completenodename") != null && !map.get("completenodename").equals("")) {//完成节点名称时间
            scOrder.setLatestNode(map.get("completenodename").toString());
            scOrder.setLastNodeTime(scProNodeOperating.getCreateTime());
            scProNodeOperating.setNodeName(map.get("completenodename").toString());
            scProNodeOperating.setNodeState(scOrder.getNodeUltraTime());//设置节点状态
        }
        if (map.get("escrowCompany") != null && !map.get("escrowCompany").equals("")) {//评估公司
            scOrder.setEscrowCompany(map.get("escrowCompany").toString());
            scProNodeOperating.setEvaluationCompany(map.get("escrowCompany").toString());
        }
        if (map.get("appraisalCost") != null && !map.get("appraisalCost").equals("")) {//评估价格
            scOrder.setAppraisalCost( Math.round(Double.parseDouble(map.get("appraisalCost").toString())* 1000000) );
            scProNodeOperating.setEvaluatedPrice( Math.round(Double.parseDouble(map.get("appraisalCost").toString())* 1000000) );
        }
        if (map.get("credit") != null && !map.get("credit").equals("")) {//征信
            scOrder.setCredit(map.get("credit").toString());
            scProNodeOperating.setCredit(map.get("credit").toString());
        }
        if (map.get("loanAmount") != null && !map.get("loanAmount").equals("")) {//申请金额
            scOrder.setLoanAmount( Math.round(Double.parseDouble(map.get("loanAmount").toString())* 1000000) );
            scProNodeOperating.setAppliedAmount( Math.round(Double.parseDouble(map.get("loanAmount").toString())* 1000000) );
        }
        if (map.get("applicationTime") != null && !map.get("applicationTime").equals("")) {//签申请时间
            scOrder.setApplicationTime(sdf.parse(map.get("applicationTime").toString()));
            scProNodeOperating.setApplicationTime(sdf.parse(map.get("applicationTime").toString()));
        }
        if (map.get("reportTime") != null && !map.get("reportTime").equals("")) {//报审时间
            scOrder.setReportTime(sdf.parse(map.get("reportTime").toString()));
            scProNodeOperating.setAuditTiem(sdf.parse(map.get("reportTime").toString()));
        }
        if (map.get("approveTime") != null && !map.get("approveTime").equals("")) {//通过时间
            scOrder.setApproveTime(sdf.parse(map.get("approveTime").toString()));
            scProNodeOperating.setApprovalTime(sdf.parse(map.get("approveTime").toString()));
        }
        if (map.get("approveMoney") != null && !map.get("approveMoney").equals("")) {//通过金额
            scOrder.setApproveMoney( Math.round(Double.parseDouble(map.get("approveMoney").toString())* 1000000) );
            scProNodeOperating.setApprovedAmount( Math.round(Double.parseDouble(map.get("approveMoney").toString())* 1000000) );
        }
        if (map.get("settlementBank") != null && !map.get("settlementBank").equals("")) {//结案银行
            scOrder.setSettlementBank(map.get("settlementBank").toString());
            scProNodeOperating.setSettlementBank(map.get("settlementBank").toString());
        }
        if (map.get("advanceFundCancel") != null && !map.get("advanceFundCancel").equals("")) {//注销时间
            scOrder.setAdvanceFundCancel(sdf.parse(map.get("advanceFundCancel").toString()));
            scProNodeOperating.setLogoffTime(sdf.parse(map.get("advanceFundCancel").toString()));
        }
        if (map.get("mortgageTime") != null && !map.get("mortgageTime").equals("")) {//办抵押时间
            scOrder.setMortgageTime(sdf.parse(map.get("mortgageTime").toString()));
            scProNodeOperating.setMortgageTime(sdf.parse(map.get("mortgageTime").toString()));
        }
        if (map.get("takeHisTime") != null && !map.get("takeHisTime").equals("")) {//取他权时间
            scOrder.setTakeHisTime(sdf.parse(map.get("takeHisTime").toString()));
            scProNodeOperating.setTakeHisTime(sdf.parse(map.get("takeHisTime").toString()));
        }
        if (map.get("loanTime") != null && !map.get("loanTime").equals("")) {//放款时间
            scOrder.setLoanTime(sdf.parse(map.get("loanTime").toString()));
            scProNodeOperating.setLoanTime(sdf.parse(map.get("loanTime").toString()));
        }
        if (map.get("loanMoney") != null && !map.get("loanMoney").equals("")) {//放款金额
            scOrder.setLoanMoney( Math.round(Double.parseDouble(map.get("loanMoney").toString())* 1000000) );
            scProNodeOperating.setLoanMoney( Math.round(Double.parseDouble(map.get("loanMoney").toString())* 1000000) );
        }
        if (map.get("loanTimeDay") != null && !map.get("loanTimeDay").equals("")) {//放款时长
            scOrder.setLoanTimeDay(Integer.parseInt(map.get("loanTimeDay").toString()));
            scProNodeOperating.setLoanDuration(Integer.parseInt(map.get("loanTimeDay").toString()));
        }
        if (map.get("repaymentDate") != null && !map.get("repaymentDate").equals("")) {//还款到期日
            scOrder.setRepaymentDate(sdf.parse(map.get("repaymentDate").toString()));
            scProNodeOperating.setNextPaymentDate(sdf.parse(map.get("repaymentDate").toString()));
        }
        if (map.get("dateOfLoan") != null && !map.get("dateOfLoan").equals("")) {//还款时间
            scOrder.setDateOfLoan(map.get("dateOfLoan").toString());
            scProNodeOperating.setRepaymentTime(map.get("dateOfLoan").toString());
        }
        if (map.get("wayOfLoan") != null && !map.get("wayOfLoan").equals("")) {//还款方式
            scOrder.setWayOfLoan(Integer.parseInt(map.get("wayOfLoan").toString()));
            scProNodeOperating.setRepaymentMode(Integer.parseInt(map.get("wayOfLoan").toString()));
        }
        if (map.get("settlementAmount") != null && !map.get("settlementAmount").equals("")) {//后台结算金额
            scOrder.setSettlementAmount( Math.round(Double.parseDouble(map.get("settlementAmount").toString())* 100) );
            scProNodeOperating.setSettlementAmount( Math.round(Double.parseDouble(map.get("settlementAmount").toString())* 100) );
        }
        if (map.get("installmentrepayment") != null && !map.get("installmentrepayment").equals("")) {//每期还款金额/月
            scOrder.setInstallmentRepayment( Math.round(Double.parseDouble(map.get("installmentrepayment").toString())* 100) );
            scProNodeOperating.setRepaymentAmount( Math.round(Double.parseDouble(map.get("installmentrepayment").toString())* 100) );
        }

        if (map.get("channelRebates") != null && !map.get("channelRebates").equals("")) {//渠道返点
            scOrder.setChannelRebates( Math.round(Double.parseDouble(map.get("channelRebates").toString())* 100) );
            scProNodeOperating.setChannelRebates( Math.round(Double.parseDouble(map.get("channelRebates").toString())* 100) );
        }
        if (map.get("foreignRebates") != null && !map.get("foreignRebates").equals("")) {//对外返点
            scOrder.setForeignRebates( Math.round(Double.parseDouble(map.get("foreignRebates").toString())* 100) );
            scProNodeOperating.setForeignRebates( Math.round(Double.parseDouble(map.get("foreignRebates").toString())* 100) );
        }
        if (map.get("nextFollowTime") != null && !map.get("nextFollowTime").equals("")) {//下次跟进时间
            scOrder.setNextFollowTime(nextsdf.parse(map.get("nextFollowTime").toString()));
            scProNodeOperating.setNextFollowTime(nextsdf.parse(map.get("nextFollowTime").toString()));
        }else{
            scOrder.setNextFollowTime(null);
            scProNodeOperating.setNextFollowTime(null);
        }
        String updatenoderemark="";
        if (map.get("updatenoderemark") != null && !map.get("updatenoderemark").equals("")) {//备注
            updatenoderemark=map.get("updatenoderemark").toString();
            scOrder.setNoteType(RemarkOperationConstant.REMARK_ORDER_UPDATENODE);
            scOrder.setNotes(updatenoderemark);
            scProNodeOperating.setUpdatenoderemark(updatenoderemark);
        }



        if(scOrder.getCurNodeId()!=null){
            ScProFlowNode CurNode = nodeManagerService.queryScProNodeById(scOrder.getCurNodeId());
            Assert.notNull(CurNode, "生产订单节点关联错误！");
            if(scProFlowNode.getSort()>=CurNode.getSort()){//当前更新节点大于历史更新节点时才进行超期计算
                tjmap.put("processId", scProFlowNode.getProcessId());
                tjmap.put("sort", (scProFlowNode.getSort() + 1) + "");
                List<Map> nextNodeMap = nodeManagerService.queryNextNodeList(tjmap);
                if (nextNodeMap.size() > 0) {//设置下一节点id名称
                    scOrder.setCurNodeId(Long.parseLong(nextNodeMap.get(0).get("id").toString()));
                    scOrder.setCurtNode(nextNodeMap.get(0).get("name").toString());
                    scProOrderTimeStateService.updateTimeStatusByScProOrder(scOrder);//同步超期消息
                } else {
                    scOrder.setCurNodeId(null);
                    scOrder.setCurtNode(null);
                    this.scProOrderTimeStateService.update_suspendScProOrderTime(scOrder.getId());//暂停超期计算
                }
            }
        }

        //判断当前节点是否关键节点，是则查询出剩余未做关键节点
        if (scProFlowNode.getIsKey() == 1) {
            tjmap.put("scorderid", scorderid);
            tjmap.put("processId", scProFlowNode.getProcessId());
            List<Map> IskeyNodeMap = nodeManagerService.queryIskeyNodeList(tjmap);
            if (IskeyNodeMap.size() == 1 && scOrder.getStatus().equals("SCORDER_STATUS02")) {
                scOrder.setStatus(ScStatusConstant.ORDER_COMPLETE);
                waitAllocationService.updateUserSetting(scOrder, "1");//成单后容量减1
                //成单时同步到CRM,新增渠道的订单不进行同步
                if (scOrder.getOrderBusId() != null) {
                    Map<String, Object> datas = new HashMap<>();
                    datas.put("mainOrderId", scOrder.getOrderId());//销售主订单id
                    datas.put("childOrderId", scOrder.getOrderBusId());//销售子订单id
                    datas.put("orderStatus", "ORF_BDZT_1");//状态 ORF_BDZT_1:成单  ORF_BDZT_2 :退单   ORF_BDZT_3:废单  ORF_BDZT_4:暂缓   ORF_BDZT_5:生产中
                    datas.put("currentUser",user);
                    orderApiService.synOrderState(datas);
                }
            }
        }
        scOrder.setNodeUltraTime(OverdueStateConstant.NORMAL);
        this.repository.saveOrUpdate(scOrder);
        this.repository.save(scProNodeOperating);
        //将备注写入crm数据库
        Map recordMap = new HashMap();
        recordMap.put("tableName", ScProOrder.TABLE_NAME);
        recordMap.put("tableId", scOrder.getId());
        recordMap.put("cusId", scOrder.getCustomerId());
        recordMap.put("ext3", scOrder.getOrderBusinessNo()); //生产编号
        recordMap.put("recordType", "OPERATION_BZ_CODE16");//备注类型
        recordMap.put("content",scProFlowNode.getName()==null?updatenoderemark:scProFlowNode.getName()+":"+updatenoderemark);//备注内容
        recordMap.put("operateUser", user.getId());//当前操作人id
        customerRecordService.saveCustomerRecord(recordMap);//写入crm

    }
}
